package com.example.dc.Controller;


import com.example.dc.Service.PersonalSerive;
import com.example.dc.Service.QuestionService;
import com.example.dc.domain.PersonalQuestion;
import com.example.dc.domain.Question;
import com.example.dc.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@Slf4j
@RequestMapping("/personal")
public class PersonalController {

    @Autowired
    private PersonalSerive personalSerive;

    @Autowired
    private QuestionService questionService;


    @GetMapping("/setquestion")
    public Result setQuestion(Integer userId){
        //先选出所有4级问题
        List<PersonalQuestion> list=personalSerive.setFourStanderQuestion();
        if(list.size()==0) return null;
        //按照父标签分类
        //1.先排序
        Collections.sort(list,(a,b)->a.getParentId()-b.getParentId());
        int last=0;
        int total=0;//总分
        List<PersonalQuestion> result=new ArrayList<>();
        for(int now=0;now<list.size();now++){
            if(now==list.size()-1||list.get(now).getParentId()!=list.get(last).getParentId()){
                Random random=new Random();
                int index=last+random.nextInt(now-last);
                result.add(list.get(index));
                last=now;
                total+=list.get(index).getScore();
            }
        }

        //选择所有三级标题
        List<Question> threeStander=questionService.getThreeStander();
        //字典映射
        Map<Integer,Integer> dict=new HashMap<>();
        for(Question question:threeStander){
            dict.put(question.getId(),question.getParentId());
        }

        //求加权倍数
        for(PersonalQuestion question:list){
            Double mutiple=100.0/total;
            question.setMultiple(mutiple);
            //获取二级标题id
            Integer secondStander=dict.get(question.getParentId());
            //把这些问题插入这个用户的个性化问题表中
            personalSerive.insertQuestion(question.getId(), userId,mutiple,secondStander);
        }
        return Result.success();
    }

    @GetMapping("healthisopen")
    public Result healthIsOpen(Integer userId){
        Integer count=personalSerive.healthIsOpen(userId);
//        定制个性化问题
        if(count==null||count<1) {
            return setQuestion(userId);
        }
        return Result.success();
    }
}
